<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocketClient</title>
</head>
<body>
<form onsubmit="return false;">
    <textarea id="message" name="message" style="width: 400px; height: 200px;"></textarea>
    <input type="button" value="发送数据" onclick="sendMessage()" />
    <input type="button" value="连接" onclick="connection()" />
    <input type="button" value="断开" onclick="closeConnection()" />
    <h3>服务器输出: </h3>
    <textarea id="responseText" style="width: 400px; height: 300px;"></textarea>
    <input type="button" value="清空" onclick="clean()" />
</form>
</body>
<script>

    let socketCache;

    function clean() {
        document.getElementById("responseText").value = '';
    }
    
    function sendMessage() {
        if ( !window.WebSocket ) {
            return;
        }

        let inputText = document.getElementById("message");
        if ( inputText.value === null || inputText.value === '' ) {
            return;
        }

        if ( socketCache.readyState === WebSocket.OPEN ) {
            socketCache.send(inputText.value);
        } else {
            alert("连接尚未开启");
        }
    }

    function connection() {
        if ( window.WebSocket ) {
            socketCache = new WebSocket("ws://localhost:29001/websocket");

            // 当服务端发送过来消息时调用, 相当于netty的channelRead0方法
            socketCache.onmessage = function (event) {
                let responseText = document.getElementById("responseText");
                responseText.value += ( event.data + '\n' );
            };

            // 连接打开监听
            socketCache.onopen = function (event) {
                let responseText = document.getElementById("responseText");
                responseText.value = '连接开启';
            };

            // 连接断开监听
            socketCache.onclose = function (event) {
                let responseText = document.getElementById("responseText");
                responseText.value += ( '连接断开' + '\n' );
            };

        } else {
            alert("您的浏览器不支持websocket");
        }
    }

    function closeConnection() {
        if ( window.WebSocket ) {
            // 主动断开连接
            socketCache.close();
        }
    }

</script>
</html>